<template>
  <el-form :model="formData" label-width="150px" ref="formData" :rules="rules">
    <el-form-item label="督办事项" prop="title">
      <el-input v-model="formData.title"></el-input>
    </el-form-item>
    <el-form-item label="督办内容" prop="content">
      <el-input type="textarea" :max="4" v-model="formData.content"></el-input>
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item label="督办编号">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="督办分类" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            @change="categorySelect"
            class="item_width"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left" v-if="item.deep === 1">{{
                item.name
              }}</span>
              <span :style="deepStyle(item)" v-else>┝{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="牵头领导" prop="leaderUserUqId">
          <user-select
            v-if="show"
            v-model="formData.leaderUserUqId"
            @getUser="getLeaderName"
          ></user-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="主要领导" prop="mainLeaderUserUqId">
          <user-select
            v-if="show"
            v-model="formData.mainLeaderUserUqId"
            @getUser="getMainLeaderName"
          ></user-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="紧急程度">
          <el-select
            v-model="formData.urgency"
            placeholder="请选择"
            class="item_width"
            @change="urgencySelect"
          >
            <el-option
              v-for="item in urgencyList"
              :key="item.keyword"
              :label="item.label"
              :value="item.keyword"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <div v-for="(item, index) in formData.responsibleList" :key="index">
      <div>
        <el-badge :value="index + 1" class="item" type="primary"></el-badge>
      </div>
      <el-row>
        <el-col>
          <el-form-item
            label="事项名称"
            :prop="'responsibleList.' + index + '.content'"
            :rules="responsibleListRules.content"
          >
            <el-input
              v-model="item.content"
              placeholder="请输入事项名称"
              maxlength="60"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="责任人"
            :prop="'responsibleList.' + index + '.responsibleUserUqId'"
            :rules="responsibleListRules.responsibleUserUqId"
          >
            <user-select
              v-if="show"
              v-model="item.responsibleUserUqId"
              @input="validateField('responsibleUserUqId')"
              @getUser="getResponsibleName"
            ></user-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任单位">
            <el-input v-model="item.responsibleUnit" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <el-row>
      <el-col
        :span="24"
        style="text-align: center;font-size: 20px;margin-bottom: 10px;margin-left: 45px"
      >
        <i @click="addResponsible" class="el-icon-circle-plus"></i>
        <i
          style="margin-left: 5px"
          @click="delResponsible"
          class="el-icon-remove"
        ></i
      ></el-col>
    </el-row>

    <!--    <el-row>-->
    <!--      <el-col :span="12">-->
    <!--        <el-form-item label="联系人" prop="linkUserUqId">-->
    <!--          <user-select-->
    <!--            v-model="formData.linkUserUqId"-->
    <!--            @getUser="getLinkName"-->
    <!--          ></user-select>-->
    <!--        </el-form-item>-->
    <!--      </el-col>-->
    <!--      <el-col :span="12"> </el-col>-->
    <!--    </el-row>-->
    <el-row>
      <el-col :span="12">
        <el-form-item label="计划开始时间" prop="planStartTime">
          <el-date-picker
            style="width: 100%"
            v-model="formData.planStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker
            style="width: 100%"
            v-model="formData.planEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="主办">
          <el-input v-model="formData.hostUnit"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="协办">
          <el-input v-model="formData.coSponsorUnit"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="发起人">
          <el-input v-model="formData.createUserName" disabled></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="事项来源">
          <el-input v-model="formData.matterSource"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="来文单位">
          <el-input v-model="formData.comeFromUnit"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="来文时间" prop="comeFromTime">
          <el-date-picker
            style="width: 100%"
            v-model="formData.comeFromTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="附件">
      <sz-common-upload
        :config="{ buttonText: '附件', uploadTip: '' }"
        v-model="formData.attachment"
        path="supervise"
        business-key="SUPERVISE"
        :auto-upload="true"
      ></sz-common-upload>
    </el-form-item>

    <el-form-item label="备注">
      <el-input v-model="formData.remark" type="textarea"></el-input>
    </el-form-item>
    <el-form-item label="是否抄送主要领导">
      <el-switch
        style="margin-left: 10px"
        v-model="formData.defaultLeaderFlag"
        active-color="#13ce66"
        active-text="是"
        inactive-text="否"
        :active-value="true"
        :inactive-value="false"
      ></el-switch>
    </el-form-item>
    <el-form-item label="汇报方式">
      <el-row>
        <el-col>
          <el-radio v-model="formData.dateType" label="WORKDAY"
            >工作日
          </el-radio>
          <el-radio v-model="formData.dateType" label="CALENDAR_DAY"
            >自然日
          </el-radio>
        </el-col>
        <el-col>
          <el-checkbox v-model="formData.isEveryday">每天</el-checkbox>
        </el-col>
        <el-checkbox-group v-model="isWeekArr">
          <el-checkbox label="1">星期一</el-checkbox>
          <el-checkbox label="2">星期二</el-checkbox>
          <el-checkbox label="3">星期三</el-checkbox>
          <el-checkbox label="4">星期四</el-checkbox>
          <el-checkbox label="5">星期五</el-checkbox>
          <el-checkbox label="6">星期六</el-checkbox>
          <el-checkbox label="7">星期日</el-checkbox>
        </el-checkbox-group>
        <el-form-item label="每月（日）" label-width="100px">
          <el-input
            v-model="formData.isMonthDay"
            placeholder="请输入指定日期（1-31号）"
          ></el-input>
        </el-form-item>
        <el-form-item
          style="margin-top: 5px"
          label="间隔（天）"
          label-width="100px"
        >
          <el-input
            v-model="formData.isIntervalDay"
            placeholder="请输入间隔天数"
          ></el-input>
        </el-form-item>
      </el-row>
    </el-form-item>
    <el-form-item>
      <span>
        <el-button type="primary" :loading="loading" @click="saveData">保存</el-button>
      </span>
    </el-form-item>
  </el-form>
</template>

<script>
import schema from "async-validator";
import _ from "lodash";

export default {
  name: "superviseAdd",
  props: {
    supervisionData: {
      type: Object,
      default: null
    },
    week: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      show: true,
      isWeekArr: [],
      responsibleListRules: {
        content: [
          { required: true, message: "请输入子事项名称", trigger: "blur" }
        ],
        responsibleUserUqId: [
          { required: true, message: "请选择责任人", trigger: "blur" },
          { required: true, message: "请选择责任人", trigger: "change" }
        ]
      },
      formData: {
        title: "",
        content: "",
        code: "",
        categoryId: "",
        dateType: "WORKDAY",
        urgency: "",
        planStartTime: null,
        planEndTime: null,
        hostUnit: "",
        coSponsorUnit: "",
        createUserName: "",
        matterSource: "",
        comeFromUnit: "",
        comeFromTime: null,
        remark: "",
        isEveryday: "",
        isMonthDay: "",
        isIntervalDay: "",
        defaultLeaderFlag: true,
        responsibleList: [
          {
            id: "",
            matterId: "",
            responsibleUserId: "",
            responsibleUserUqId: "",
            responsibleName: "",
            responsibleUnit: "",
            content: "",
            progress: "",
            status: ""
          }
        ]
      },

      rules: {
        title: [{ required: true, message: "请输入督办事项", trigger: "blur" }],
        content1: [
          { required: true, message: "请输入事项名称", trigger: "blur" }
        ],
        code: [{ required: true, message: "请输入督办编码", trigger: "blur" }],
        content: [
          { required: true, message: "请输入督办内容", trigger: "blur" }
        ],
        leaderUserUqId: [
          { required: true, message: "请输入牵头领导", trigger: "blur" }
        ],
        mainLeaderUserUqId: [
          { required: true, message: "请输入主要领导", trigger: "blur" }
        ],
        responsibleUserUqId: [
          { required: true, message: "请选择责任人", trigger: "blur" }
        ],
        planStartTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" }
        ],
        planEndTime: [
          { required: true, message: "请选择结束时间", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "blur" },
          {
            required: true,
            message: "请选择分类",
            trigger: "change"
          }
        ]
      },
      categoryList: [], //督办分类
      currentTokenUser: JSON.parse(window.sessionStorage.getItem("userInfo")),
      urgencyList: this.getDictionary("SUPERVISION_EMERGENCY") // 紧急程度
    };
  },
  created() {},
  mounted() {
    this.getCategoryTree();
    this.formData.createUserName = this.currentTokenUser.user.name;
    //编辑
    this.supervisionData !== null &&
      Object.assign(this.formData, this.supervisionData);
    this.isWeekArr = this.week !== null ? this.week : [];
  },
  methods: {
    initData() {
      this.formData = {
        title: "",
        content: "",
        code: "",
        categoryId: "",
        dateType: "WORKDAY",
        urgency: "",
        planStartTime: null,
        planEndTime: null,
        hostUnit: "",
        coSponsorUnit: "",
        createUserName: "",
        matterSource: "",
        comeFromUnit: "",
        comeFromTime: null,
        remark: "",
        isEveryday: "",
        isMonthDay: "",
        isIntervalDay: "",
        defaultLeaderFlag: true,
        responsibleList: [
          {
            id: "",
            matterId: "",
            responsibleUserId: "",
            responsibleUserUqId: "",
            responsibleName: "",
            responsibleUnit: "",
            content: "",
            progress: "",
            status: ""
          }
        ]
      };
      this.getCategoryTree();
      this.formData.createUserName = this.currentTokenUser.user.name;
    },
    // 联系人
    getLinkName(val) {
      this.formData.linkUserId = val.origId;
      this.formData.linkUserName = val.userNames;
    },
    // 牵头领导名称，原始id获取
    getLeaderName(val) {
      this.formData.leaderUserId = val.origId;
      this.formData.leaderName = val.userNames;
    },
    // 主要领导名称，原始id获取
    getMainLeaderName(val) {
      this.formData.mainLeaderUserId = val.origId;
      this.formData.mainLeaderUserName = val.userNames;
    },
    validateField(type) {
      console.log(type);
      this.$refs.formData.validateField(type);
    },

    // 责任人名称，原始id
    getResponsibleName(val) {
      let arr = [];
      let obj = "";
      let obj1 = [];
      let obj2 = [];
      let obj3 = [];
      this.formData.responsibleList.map(item => {
        if (item.responsibleUserUqId == val.uuid) {
          item.responsibleUserId = val.origId;
          item.responsibleName = val.userNames;
          item.responsibleUnit = val.deptNames;
        }
        arr.push(item.responsibleUserId);
        for (let i = 0; i < arr.length; i++) {
          for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) {
              arr.splice(j, 1);
              j--;
            }
          }
        }
        obj = arr.join(",");
        obj1.push(item.responsibleName);
        for (let i = 0; i < obj1.length; i++) {
          for (let j = i + 1; j < obj1.length; j++) {
            if (obj1[i] == obj1[j]) {
              obj1.splice(j, 1);
              j--;
            }
          }
        }
        this.formData.responsiblePerson = obj1.join(",");
        obj2.push(item.responsibleUnit);
        for (let i = 0; i < obj2.length; i++) {
          for (let j = i + 1; j < obj2.length; j++) {
            if (obj2[i] == obj2[j]) {
              obj2.splice(j, 1);
              j--;
            }
          }
        }
        this.formData.responsibleUnit = obj2.join(",");
        obj3.push(item.responsibleUserUqId);
        for (let i = 0; i < obj3.length; i++) {
          for (let j = i + 1; j < obj3.length; j++) {
            if (obj3[i] == obj3[j]) {
              obj3.splice(j, 1);
              j--;
            }
          }
        }
        this.formData.responsibleUserUqId = obj3.join(",");
      });
      this.formData.responsibleUserId = "," + obj + ",";
    },
    // 紧急程度
    urgencySelect(val) {
      this.urgencyList.map(item => {
        if (item.keyword === val) {
          this.formData.urgencyName = item.label;
        }
      });
    },
    // 分类
    categorySelect(val) {
      this.categoryList.map(item => {
        if (item.id === val) {
          this.formData.categoryName = item.name;
        }
      });
    },
    // 获取督办分类
    getCategoryTree() {
      this.API.getCategoryTree({ type: "SUPERVISE", parentId: 0 }).then(res => {
        if (res.data) {
          this.categoryList = [];
          this.setCategoryDeep(res.data, 1);
        }
      });
    },
    setCategoryDeep(data, deep) {
      data.map(item => {
        item.deep = deep;
        let nextDeep = deep + 1;
        this.categoryList.push(item);
        if (item.children) {
          item.children = this.setCategoryDeep(item.children, nextDeep);
        }
      });
      return data;
    },
    // 设置loading防止连点
    setLoading() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 3000);
    },
    // 保存数据
    saveData() {
      this.formData.isWeek = this.isWeekArr.join(",");
      this.$refs["formData"].validate(valid => {
        if (valid) {
          this.setLoading();
          if (
            this.compareDate(
              this.formData.planStartTime,
              this.formData.planEndTime
            )
          ) {
            this.warningNotify("提示", "开始时间必须小于结束时间");
            return;
          }
          let tem = {
            supervisionMatter: this.formData,
            responsibleList: _.clone(this.formData.responsibleList)
          };
          delete tem.supervisionMatter.responsibleList;
          this.$emit("saveData", tem);
          this.formData = {
            title: "",
            content: "",
            code: "",
            categoryId: "",
            dateType: "WORKDAY",
            urgency: "",
            planStartTime: null,
            planEndTime: null,
            hostUnit: "",
            coSponsorUnit: "",
            createUserName: "",
            matterSource: "",
            comeFromUnit: "",
            comeFromTime: null,
            remark: "",
            isEveryday: "",
            isMonthDay: "",
            isIntervalDay: "",
            defaultLeaderFlag: true,
            responsibleList: [
              {
                id: "",
                matterId: "",
                responsibleUserId: "",
                responsibleUserUqId: "",
                responsibleName: "",
                responsibleUnit: "",
                content: "",
                progress: "",
                status: ""
              }
            ]
          };
          this.isWeekArr = [];
          this.show = false;
          let t = setTimeout(() => {
            this.show = true;
          }, 0);
        } else {
          return false;
        }
      });
    },
    addResponsible() {
      // if (this.responsibleList.length >= 3) {
      //   this.warning("最多添加三条");
      //   return;
      // }
      this.formData.responsibleList.push({
        id: "",
        matterId: "",
        responsibleUserId: "",
        responsibleUserUqId: "",
        responsibleName: "",
        responsibleUnit: "",
        content: "",
        progress: "",
        status: ""
      });
    },
    delResponsible() {
      this.formData.responsibleList.length >= 2 &&
        this.formData.responsibleList.splice(-1, 1);
    }
  }
};
</script>

<style scoped></style>
